﻿using Autofac;
using Autofac.Features.AttributeFilters;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace AutoRegistDependency.Attributes
{
    /// <summary>
    /// 配置文件实体模型特性。标记在类上。将会把配置文件内读取到的json文件转为对应类的实例。读取的规则和.net core原生读取规则相同。
    /// Component、Confignature、Job以及ConfigurationProperties特性在同一个类上只能有一个。
    /// Configure the physical model properties of the file. Mark on class. 
	/// The JSON file read from the configuration file will be converted into an instance of the corresponding class.
    /// The reading rules are the same as the native reading rules for. net core.
    /// The Component, Configure, Job, and ConfigurationProperties attributes can only have one on the same class.
    /// </summary>
    [Unique]
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    public sealed class ConfigurationPropertiesAttribute : ParameterFilterAttribute
    {
        /// <summary>
        /// 配置项的路径
        /// </summary>
        public string Path { get; set; }
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="path">配置项的path。The path of the configuration item</param>
        public ConfigurationPropertiesAttribute(string path)
        {
            Path = path;
        }

        public override object ResolveParameter(ParameterInfo parameter, IComponentContext context)
        {
            IConfiguration configuration = context.Resolve<IConfiguration>();
            return configuration.GetSection(Path).Get(parameter.ParameterType);
        }

        public override bool CanResolveParameter(ParameterInfo parameter, IComponentContext context)
        {
            return true;
        }
    }
}
